"""
Case Type   : 系统内部使用工具
Case Name   : gs_ctl restart指定-m的值为immediate，重新启动是否成功
Create At   : 2021/01/18
Owner       : opentestcase015
Description :
    1.查看集群状态是否正常
    2.restart启动备机
    3.查看集群、备机状态
    4.恢复环境
Expect      :
    1.查看集群状态正常成功
    2.restart成功
    3.集群、备机状态正常
    4.成功
History     :
    Modified by lopentestcase027 2023/1/11: 优化用例步骤格式及一主两备判断方式
    Modified by opentestcase042 2023/3/24: 优化用例,增加等待时间后再查询备机集群状态
"""

import unittest
import os
import time
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

LOG = Logger()
primary_sh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != primary_sh.get_node_num(), '非1+2环境不执行')
class LogicalReplication(unittest.TestCase):
    def setUp(self):
        LOG.info(f'--------{os.path.basename(__file__)} start--------')
        self.constant = Constant()
        self.PrimaryNode = Node('PrimaryDbUser')
        self.user_node = Node('Standby1DbUser')
        self.sh_standby = CommonSH('Standby1DbUser')

    def test_system_internal_tools(self):
        LOG.info('--------step1:查看集群状态    expect:集群状态正常--------')
        status = self.sh_standby.get_db_cluster_status(param='status')
        self.assertTrue(status)

        LOG.info('--------step2:重启数据库备机    expect:启动成功--------')
        excute_cmd = f'''
                source {macro.DB_ENV_PATH};
                gs_ctl restart -D {macro.DB_INSTANCE_PATH} -M standby \
                -m immediate;'''
        LOG.info(excute_cmd)
        msg = self.user_node.sh(excute_cmd).result()
        LOG.info(msg)
        self.assertIn(self.constant.RESTART_SUCCESS_MSG, msg)

        LOG.info('------step3:查看集群、备机状态  expect:集群、备机状态正常------')
        time.sleep(5)
        status = self.sh_standby.get_db_cluster_status(param='detail')
        LOG.info(status)
        self.assertTrue(len(status.splitlines()) >= 10)
        self.assertIn('Standby Normal', status.splitlines()[-2])
        self.assertTrue(self.constant.CLUSTER_NORMAL_MSG in status)

    def tearDown(self):
        LOG.info('--------step4:恢复环境     expect:成功--------')
        restart = self.sh_standby.restart_db_cluster()
        LOG.info(restart)
        self.assertTrue(restart)
        status = self.sh_standby.get_db_cluster_status(param='detail')
        LOG.info(status)
        self.assertTrue(self.constant.CLUSTER_NORMAL_MSG in status)
        LOG.info(f'--------{os.path.basename(__file__)} end--------')
